var fs = require("fs"),
    path = require("path"),
    sitesJsonPath = path.join(global.rootPath, "/assets/json/sites.json");

var SiteModel = function(_id, _name, _url, _index, _remark, _pId) {

    this.id = _id;
    this.name = _name || "";
    this.pId = _pId || 'root';
    this.url = _url || "";
    this.index = _index || 0;
    this.date = new Date();
    this.remark = _remark || "";
};

SiteModel.prototype = {

    add: function(_callBack) {

        if (this.select(this.id) != null) {
            return this.edit(this.id, _callBack);
        }
        var sites = global.sites;
        sites.push(this.getAttr());
        saveJson(_callBack);
    },
    del: function(_id, _callBack) {

        var sites = global.sites;
        i = sites.length - 1;
        for (i; i >= 0; i--) {
            if (sites[i].id == _id) break;
        }
        if (i >= 0) {
            sites.splice(i, 1);
            saveJson(_callBack);
        } else {
            _callBack({
                result: false
            });
        }
    },
    edit: function(_id, _callBack) {

        var sites = global.sites;
        i = sites.length - 1;
        for (i; i >= 0; i--) {
            if (sites[i].id == _id) break;
        }
        if (i >= 0) {
            sites[i].name = this.name;
            sites[i].url = this.url;
            sites[i].index = this.index;
            sites[i].remark = this.remark;
            saveJson(_callBack);
        } else {
            _callBack({
                result: false
            });
        }
    },
    select: function(_id) {

        var sites = global.sites,
            i = sites.length - 1;
        for (i; i >= 0; i--) {
            if (sites[i].id == _id) break;
        };
        return i >= 0 ? sites[i] : null;
    },
    getAttr: function() {

        return {
            id: this.id,
            name: this.name,
            pId: this.pId,
            url: this.url,
            index: this.index,
            createDate: this.date.format("yyyy-MM-dd hh:mm"),
            remark: this.remark
        };
    }
};

function saveJson(_callBack) {

    fs.writeFile(sitesJsonPath, JSON.stringify(global.sites, null, "\t"), function(err) {
        if (err) {
            console.log(err);
            if (_callBack) _callBack({
                result: false
            });
        }
        global.sites.sort(function(a, b) {
            return a.index > b.index ? -1 : 1;
        });
        if (_callBack)
            _callBack({
                result: true
            });
    });
};

module.exports = SiteModel;